module key_led # (
    parameter T = 10_000_000			// 0.2s时钟周期数
)
(
	input				clk_50m,		// 50MHz时钟信号
	input				rst_n,			// 复位信号
	input 	[3:0]		key,			// 按键输入信号
	output reg [3:0]	led				// LED输出信号
);

	// 按键状态
	localparam FLOW_LEFT	= 4'b0001;	// 流水灯自右向左依次点亮
	localparam FLOW_RIGHT	= 4'b0010;	// 流水灯自左向右依次点亮
	localparam LED_FLASH	= 4'b0100;	// 四个led灯同时闪烁
	localparam ALL_LIGHT	= 4'b1000;	// 四个led灯全亮
	// 计数器
	reg [23:0] cnt = 0;
	always @ (posedge clk_50m or negedge rst_n) begin
		if (!rst_n) cnt <= 0;
		else if (cnt < T - 1) cnt <= cnt + 1;
		else cnt <= 0;
	end
	
	// 根据按键及状态计数器更改led
	always @ (posedge clk_50m or negedge rst_n) begin
		if (!rst_n) led <= 4'b1111;
		else
			case (key)
				FLOW_LEFT	: begin
					if (led == 4'b1111 || led == 4'b0000) led <= 4'b0001;
					else if (cnt == T - 1) led <= {led[2:0], led[3]};
					else led <= led;
				end
				FLOW_RIGHT	: begin
					if (led == 4'b1111 || led == 4'b0000) led <= 4'b0001;
					else if (cnt == T - 1) led <= {led[0], led[3:1]};
					else led <= led;
				end
				LED_FLASH	: begin
					if (led != 4'b1111 && led != 4'b0000) led <= 4'b1111;
					else if (cnt == T - 1) led <= ~led;
					else led <= led;
				end
				ALL_LIGHT	: led <= 4'b1111;
				default		: led <= 4'b0000;
			endcase
	end
	
endmodule
